﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using CoreLibrary;
using CoreLibrary.Sql;
using Entities.DataBase.Persistent;

namespace Entities.DataBase.Sql {

    public class ListStocksByIds : ISqlQuery<List<Stock>> {

        private readonly List<int> _stockIds;
        private readonly string _tableName;

        public ListStocksByIds(string tableName, List<int> stockIds) {
            _stockIds  = stockIds;
            _tableName = tableName;
        }

        public string GetSQL() {
            return string.Format(
                @"
                    select *
                    from {0}
                    where id IN ({1});
                ",
                _tableName,
                StringUtil.Join(",", _stockIds.Select(campaignId => string.Format(@"'{0}'", campaignId)).ToList())
            );
        }

        public void SetParameters(SqlCommand command) {
            command.CommandType = CommandType.Text;
        }

        public List<Stock> GetResult(SqlConnection conn, SqlDataReader result) {
            var stocks = new List<Stock>();
            if (result.HasRows) {
                while (result.Read()) {
                    stocks.Add(Read(result));
                }
            }
            return stocks;
        }

        private static Stock Read(SqlDataReader result) {
            return new Stock {
                Id              = (int) result["ID"],
                Guid            = Util.GetString(result["GUID"]),
                Count           = (int) result["STOCK"],
                ProductId       = Util.GetString(result["PRODUCT_ID"]),
                Location        = (int)result["LOCATION"],
                Price           = (decimal) result["PRICE"],
                Postage         = (decimal)result["POSTAGE"],
                PriceCurrency   = Util.GetString(result["PRICE_CURRENCY"]),
                PostageCurrency = Util.GetString(result["POSTAGE_CURRENCY"]),
                DateCreated     = (DateTime)result["DATE_CREATED"],
                DateUpdated     = (DateTime)result["DATE_UPDATED"]
            };
        }

    }

}